/**
 * API请求封装模块
 * 自动处理Token认证、错误处理和请求拦截
 */
class ApiClient {
    constructor() {
        this.baseURL = 'http://api.dadefeng.com';
        this.timeout = 30000; // 30秒超时
        this.retryCount = 3; // 重试次数
        this.retryDelay = 1000; // 重试延迟
        
        this.init();
    }

    init() {
        // 设置请求拦截器
        this.setupInterceptors();
        
        // 监听认证状态变更
        if (window.authManager) {
            window.authManager.onAuthChange('login', () => {
                console.log('用户已登录，API客户端已更新');
            });
            
            window.authManager.onAuthChange('logout', () => {
                console.log('用户已退出，API客户端已清除认证信息');
            });
        }
    }

    /**
     * 设置请求拦截器
     */
    setupInterceptors() {
        // 这里可以添加全局请求拦截逻辑
        // 由于是前端环境，我们使用fetch拦截的方式
    }

    /**
     * 构建完整URL
     */
    buildUrl(endpoint) {
        if (endpoint.startsWith('http://') || endpoint.startsWith('http://')) {
            return endpoint;
        }
        return `${this.baseURL}${endpoint.startsWith('/') ? endpoint : '/' + endpoint}`;
    }

    /**
     * 获取请求头信息
     */
    getHeaders(additionalHeaders = {}) {
        const headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            ...additionalHeaders
        };

        // 添加认证头
        if (window.authManager) {
            const authHeaders = window.authManager.getAuthHeaders();
            Object.assign(headers, authHeaders);
        }

        return headers;
    }

    /**
     * 处理响应
     */
    async handleResponse(response) {
        const contentType = response.headers.get('content-type');
        
        // 处理空响应
        if (response.status === 204) {
            return { success: true, data: null };
        }

        // 解析响应数据
        let data;
        if (contentType && contentType.includes('application/json')) {
            data = await response.json();
        } else {
            data = await response.text();
        }

        // 检查HTTP状态码
        if (response.ok) {
            return { success: true, data, status: response.status };
        } else {
            return this.handleErrorResponse(response, data);
        }
    }

    /**
     * 处理错误响应
     */
    async handleErrorResponse(response, data) {
        let errorMessage = '请求失败';
        
        if (typeof data === 'object' && data !== null) {
            errorMessage = data.message || data.error || errorMessage;
        } else if (typeof data === 'string') {
            errorMessage = data;
        }

        // 处理认证错误
        if (response.status === 401) {
            console.warn('认证失败，尝试刷新token');
            const refreshSuccess = await this.handleAuthError();
            if (refreshSuccess) {
                // 重试原请求
                return this.retryRequest(response.config);
            } else {
                // 检查是否是发送验证码等不需要认证的接口
                const endpoint = response.url || '';
                if (endpoint.includes('/srmddf/sys/sms') || endpoint.includes('/sms')) {
                    console.log('发送验证码接口认证失败，不进行重定向');
                    // 不跳转，直接返回错误
                } else {
                    // 跳转到登录页面
                    this.handleAuthFailure();
                }
            }
        }

        // 处理禁止访问错误
        if (response.status === 403) {
            errorMessage = '权限不足，无法访问此资源';
        }

        // 处理资源不存在错误
        if (response.status === 404) {
            errorMessage = '请求的资源不存在';
        }

        // 处理服务器错误
        if (response.status >= 500) {
            errorMessage = '服务器错误，请稍后重试';
        }

        return {
            success: false,
            error: errorMessage,
            status: response.status,
            data
        };
    }

    /**
     * 处理认证错误
     */
    async handleAuthError() {
        if (window.authManager) {
            try {
                // 检查token是否即将过期
                if (window.authManager.isTokenExpiringSoon()) {
                    const refreshSuccess = await window.authManager.refreshToken();
                    if (refreshSuccess) {
                        return true;
                    }
                }
            } catch (error) {
                console.error('Token刷新失败:', error);
            }
        }
        return false;
    }

    /**
     * 处理认证失败
     */
    handleAuthFailure() {
        if (window.authManager) {
            window.authManager.clearAuth();
        }
        
        // 跳转到登录页面
        const currentUrl = encodeURIComponent(window.location.href);
        window.location.href = `index.html?redirect=${currentUrl}`;
    }

    /**
     * 重试请求
     */
    async retryRequest(config) {
        // 这里需要保存原始请求配置以便重试
        // 由于fetch的局限性，我们需要在请求前保存配置
        console.log('重试请求...');
        // 简化处理，实际应用中需要更完善的重试机制
        return null;
    }

    /**
     * 通用请求方法
     */
    async request(endpoint, options = {}) {
        const url = this.buildUrl(endpoint);
        const headers = this.getHeaders(options.headers);
        
        const config = {
            ...options,
            headers,
            // 保存配置用于重试
            _originalConfig: { endpoint, options }
        };

        try {
            const response = await fetch(url, config);
            return await this.handleResponse(response);
        } catch (error) {
            console.error('请求失败:', error);
            
            // 处理网络错误
            if (error.name === 'TypeError' && error.message.includes('NetworkError')) {
                return {
                    success: false,
                    error: '网络连接失败，请检查网络设置',
                    code: 'NETWORK_ERROR'
                };
            }

            // 处理超时错误
            if (error.name === 'AbortError') {
                return {
                    success: false,
                    error: '请求超时，请稍后重试',
                    code: 'TIMEOUT_ERROR'
                };
            }

            return {
                success: false,
                error: error.message || '请求失败',
                code: 'UNKNOWN_ERROR'
            };
        }
    }

    /**
     * GET请求
     */
    async get(endpoint, params = {}, options = {}) {
        let url = endpoint;
        
        // 添加查询参数
        if (Object.keys(params).length > 0) {
            const searchParams = new URLSearchParams();
            Object.keys(params).forEach(key => {
                if (params[key] !== null && params[key] !== undefined) {
                    searchParams.append(key, params[key]);
                }
            });
            url += (endpoint.includes('?') ? '&' : '?') + searchParams.toString();
        }

        return this.request(url, {
            method: 'GET',
            ...options
        });
    }

    /**
     * POST请求
     */
    async post(endpoint, data = {}, options = {}) {
        return this.request(endpoint, {
            method: 'POST',
            body: JSON.stringify(data),
            ...options
        });
    }

    /**
     * PUT请求
     */
    async put(endpoint, data = {}, options = {}) {
        return this.request(endpoint, {
            method: 'PUT',
            body: JSON.stringify(data),
            ...options
        });
    }

    /**
     * DELETE请求
     */
    async delete(endpoint, options = {}) {
        return this.request(endpoint, {
            method: 'DELETE',
            ...options
        });
    }

    /**
     * PATCH请求
     */
    async patch(endpoint, data = {}, options = {}) {
        return this.request(endpoint, {
            method: 'PATCH',
            body: JSON.stringify(data),
            ...options
        });
    }

    /**
     * 文件上传
     */
    async upload(endpoint, file, additionalData = {}, options = {}) {
        const formData = new FormData();
        formData.append('file', file);
        
        // 添加额外数据
        Object.keys(additionalData).forEach(key => {
            formData.append(key, additionalData[key]);
        });

        const headers = this.getHeaders();
        // 移除Content-Type，让浏览器自动设置
        delete headers['Content-Type'];

        return this.request(endpoint, {
            method: 'POST',
            body: formData,
            headers,
            ...options
        });
    }

    /**
     * 批量请求
     */
    async batch(requests) {
        const promises = requests.map(req => {
            const { method = 'GET', endpoint, data, options } = req;
            switch (method.toUpperCase()) {
                case 'GET':
                    return this.get(endpoint, data, options);
                case 'POST':
                    return this.post(endpoint, data, options);
                case 'PUT':
                    return this.put(endpoint, data, options);
                case 'DELETE':
                    return this.delete(endpoint, options);
                case 'PATCH':
                    return this.patch(endpoint, data, options);
                default:
                    return Promise.reject(new Error(`不支持的请求方法: ${method}`));
            }
        });

        try {
            const results = await Promise.all(promises);
            return { success: true, data: results };
        } catch (error) {
            return { success: false, error: error.message };
        }
    }

    /**
     * 请求重试机制
     */
    async retry(endpoint, options = {}) {
        let lastError;
        
        for (let i = 0; i < this.retryCount; i++) {
            try {
                const result = await this.request(endpoint, options);
                if (result.success) {
                    return result;
                }
                lastError = result.error;
                
                // 如果是认证错误，不重试
                if (result.status === 401) {
                    break;
                }
                
                // 延迟重试
                if (i < this.retryCount - 1) {
                    await new Promise(resolve => setTimeout(resolve, this.retryDelay * (i + 1)));
                }
            } catch (error) {
                lastError = error.message;
                
                // 延迟重试
                if (i < this.retryCount - 1) {
                    await new Promise(resolve => setTimeout(resolve, this.retryDelay * (i + 1)));
                }
            }
        }
        
        return {
            success: false,
            error: lastError || '请求失败，已达到最大重试次数'
        };
    }

    /**
     * 健康检查
     */
    async healthCheck() {
        try {
            const response = await this.get('/health', {}, { timeout: 5000 });
            return response.success;
        } catch (error) {
            return false;
        }
    }

    /**
     * 设置基础URL
     */
    setBaseURL(url) {
        this.baseURL = url;
    }

    /**
     * 设置超时时间
     */
    setTimeout(timeout) {
        this.timeout = timeout;
    }

    /**
     * 设置重试配置
     */
    setRetryConfig(count, delay) {
        this.retryCount = count;
        this.retryDelay = delay;
    }
}

// 业务API接口封装
class BusinessApi {
    constructor() {
        this.client = new ApiClient();
    }

    // 用户相关API
    async checkUserExists(openid) {
        return this.client.get('/check-user', { openid });
    }

    async sendSmsCode(mobile) {
        console.log('📞 BusinessApi.sendSmsCode 被调用，手机号:', mobile);
        
        try {
            // 直接使用fetch，避免复杂的客户端逻辑
            const response = await fetch('http://api.dadefeng.com/srmddf/sys/sms', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ mobile })
            });
            
            console.log('📞 API响应状态:', response.status);
            
            if (response.ok) {
                const data = await response.json();
                console.log('📞 API响应数据:', data);
                return { success: true, data };
            } else {
                const errorData = await response.text();
                console.log('📞 API错误响应:', errorData);
                return { success: false, message: `请求失败: ${response.status}` };
            }
        } catch (error) {
            console.error('📞 发送验证码网络错误:', error);
            return { success: false, message: '网络错误，请检查连接' };
        }
    }

    async register(userData) {
        console.log('📝 BusinessApi.register 被调用，数据:', userData);
        
        try {
            // 直接使用fetch，避免复杂的客户端逻辑和重定向
            const response = await fetch('http://api.dadefeng.com/srmddf/company/attest', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(userData)
            });
            
            console.log('📝 注册API响应状态:', response.status);
            
            if (response.ok) {
                const data = await response.json();
                console.log('📝 注册API响应数据:', data);
                return { success: true, data };
            } else {
                const errorData = await response.text();
                console.log('📝 注册API错误响应:', errorData);
                return { success: false, message: `注册失败: ${response.status}` };
            }
        } catch (error) {
            console.error('📝 注册网络错误:', error);
            return { success: false, message: '网络错误，请检查连接' };
        }
    }

    async mattest(userData) {
        return this.client.post('/srmddf/company/mattest', userData);
    }

    async getUserProfile(openid) {
        return this.client.get('/user/profile', { openid });
    }

    // 控制面板相关API
    async getDashboardStats() {
        return this.client.get('/dashboard/stats');
    }

    async getRecentActivities(params = {}) {
        return this.client.get('/dashboard/activities', params);
    }

    async createActivity(activityData) {
        return this.client.post('/dashboard/activities', activityData);
    }

    // 功能模块相关API
    async getSalesQuotations(params = {}) {
        return this.client.get('/sales/quotations', params);
    }

    async getPromotionProducts(params = {}) {
        return this.client.get('/promotion/products', params);
    }

    async getProcurementSuppliers(params = {}) {
        return this.client.get('/procurement/suppliers', params);
    }

    async getInvestmentProjects(params = {}) {
        return this.client.get('/investment/projects', params);
    }

    // 个人中心相关API
    async updateUserProfile(profileData) {
        return this.client.put('/user/profile', profileData);
    }

    async changePassword(passwordData) {
        return this.client.post('/user/change-password', passwordData);
    }

    async getUserOrders(params = {}) {
        return this.client.get('/user/orders', params);
    }

    async getUserStats() {
        return this.client.get('/user/stats');
    }
}

// 创建全局实例
window.apiClient = new ApiClient();
window.businessApi = new BusinessApi();

// 导出类（供模块化使用）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { ApiClient, BusinessApi };
}